package com.example.anew.journey.mynewjourney.customview;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.example.anew.journey.mynewjourney.MyAnimationListener;
import com.example.anew.journey.mynewjourney.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.jesse.nativelogger.NLogger;


/**
 * 杭州惟君医疗科技有限公司11
 * Created by 20433 on 2018/3/19
 */

public class MyCardiacDetectionCustomView extends View {
    private int controlmargin = 20; //圆环距离边框的距离
    private  int ringwidth = 20;  //环的粗细
    private Paint mpaint;
    private int greatcirclebrushcolor; //大圆的背景画笔颜色

    private int controlsheight;  //控件高度
    private int controlswidth;  //控件宽度
    private int greatcircleradius ;//大圆半径
    private int smallroundradius; //小内圆的半径
    private Paint npaint;
    private int smallroundcolor ; //小圆的背景画笔颜色
    private Paint rpaint;
    private int ringcolor ; //圆环颜色
    private Paint underparpaint;
    private ObjectAnimator animator;

    public float getRingsweepAngle() {
        return ringsweepAngle;
    }
    public void setRingsweepAngle(float ringsweepAngle) {
        this.ringsweepAngle = ringsweepAngle;
        invalidate();
    }
    private float ringsweepAngle = 0.5f;
    private Paint tpaint;

    public void setUppertest(String uppertest) {
        this.uppertest = uppertest;
        invalidate();
    }

    private String uppertest ;  //上部分文字
    private String underpartwordtext ;  //小部分文字
    private int smallroundinsidetextcolor ; //小圆内文字颜色
    private int smallroundinsidetextsize ; //小圆内文字大小

    public void setFlag(boolean mflag) {
        this.flag = mflag;
        NLogger.e("TAG","flag=MyCardiacDetectionCustomView==flag===============>"+flag);
        invalidate();
    }

    private boolean flag = true; //默认显示小圆提示信息  true 显示小圆提示信息 false 显示 心电图
    private Paint epaint;
    private int ElectrocardiogramPeakHeight; //心电图峰高
    private int Xoffset = 20; //x轴偏移量
    private int offsetShiftNumber =0; //偏移次数
    private boolean isElectrocardiogram = true; //是否测试 true 测试 false 停止测试；
    private int maxcrest ; //小圆内最多可存在多少个波峰
    private int maximum;
    private int smallroundinsidetextunderparpaintsize; //小圈下部文字大小
    private float mtringsweepAngle;


    private List<Integer> data = new ArrayList<Integer>();
    private int MaxDataSize ;
    private int YScale = 20;
    private Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    invalidate();
                    break;
                case 1:
                    if(ringsweepAngle < mtringsweepAngle){
                        ringsweepAngle ++;
                    }else if(ringsweepAngle == mtringsweepAngle){
                        ringsweepAngle = mtringsweepAngle;
                    }else {
                        //ringsweepAngle = mtringsweepAngle;
                        ringsweepAngle = 0.5f;
                    }
                    invalidate();
                    postInvalidate();
                    break;
            }
        }
    };
    private Path mpath;
    private Random random;

    public MyCardiacDetectionCustomView(Context context) {
        this(context,null);
    }

    public MyCardiacDetectionCustomView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyCardiacDetectionCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCardiacDetectionCustomView);
        greatcirclebrushcolor =  ta.getColor(R.styleable.MyCardiacDetectionCustomView_custom_view_great_circle_bg,0xffffffff);
        smallroundcolor =  ta.getColor(R.styleable.MyCardiacDetectionCustomView_custom_view_small_round_bg,0xffE4EEFF);//5582b1ff
        ringcolor =  ta.getColor(R.styleable.MyCardiacDetectionCustomView_custom_view_ring_color,0xff1472FF);
        smallroundinsidetextcolor =  ta.getColor(R.styleable.MyCardiacDetectionCustomView_custom_view_small_round_inside_text_color,0xff323232);
        smallroundinsidetextsize =  ta.getInteger(R.styleable.MyCardiacDetectionCustomView_custom_view_small_round_inside_text_size,55);
        smallroundinsidetextunderparpaintsize =  ta.getInteger(R.styleable.MyCardiacDetectionCustomView_custom_view_small_round_inside_under_part_text_size,25);
        uppertest =  ta.getString(R.styleable.MyCardiacDetectionCustomView_custom_view_upper_test);
        underpartwordtext =  ta.getString(R.styleable.MyCardiacDetectionCustomView_custom_view_under_part_word_text);
        ta.recycle();  //注意回收
        init();
    }
    // 初始化
    private void init() {
        // 大圆的背景画笔
        mpaint = new Paint();
        mpaint.setAntiAlias(true);
        mpaint.setColor(greatcirclebrushcolor);
        // 小内圆的背景画笔
        npaint = new Paint();
        npaint.setAntiAlias(true);
        npaint.setColor(smallroundcolor);
        //圆环画笔
        rpaint = new Paint();
        rpaint.setAntiAlias(true);
        rpaint.setColor(ringcolor);
        rpaint.setStyle(Paint.Style.STROKE);
        rpaint.setStrokeWidth(ringwidth);
        rpaint.setStrokeCap(Paint.Cap.ROUND);

        tpaint = new Paint();
        tpaint.setAntiAlias(true);
        tpaint.setColor(smallroundinsidetextcolor);
        tpaint.setStrokeWidth(5);
        tpaint.setTextSize(smallroundinsidetextsize);

        underparpaint = new Paint();
        underparpaint.setAntiAlias(true);
        underparpaint.setColor(smallroundinsidetextcolor);
        underparpaint.setStrokeWidth(3);
        underparpaint.setTextSize(smallroundinsidetextunderparpaintsize);

        epaint = new Paint();
        epaint.setAntiAlias(true);
        epaint.setStyle(Paint.Style.STROKE);
        epaint.setStrokeWidth(3);

        random = new Random();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       int width =  MeasureSpec.getSize(widthMeasureSpec);
       int height =  MeasureSpec.getSize(heightMeasureSpec);
       int controls = width >= height ? width:height;
        controlswidth = controls;
        controlsheight = controls;
        greatcircleradius = (width -(2*controlmargin))/2;
        smallroundradius = (greatcircleradius - ringwidth);
        setMeasuredDimension(controlswidth, controlsheight);
        maxcrest = (2*smallroundradius)/Xoffset;

        MaxDataSize = (2*smallroundradius) / Xoffset +1;
        mpath = new Path();
        mpath.moveTo(controlmargin+ringwidth,controlswidth/2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // todo 绘制大背景圆
        drawGreatCircler(canvas);
        // todo 绘制小内圆
        drawSmallRound(canvas);
        if(flag){
            NLogger.e("TAG","flag===MyCardiacDetectionCustomView===============>"+flag);
            // todo 绘制默认的视图
            drawContent(canvas);
        }
        //todo 绘制圆环
        drawRing(canvas);
        //todo 绘制心电图

    }

    // todo 绘制默认的视图
    private void drawContent(Canvas canvas) {
        Rect rect = new Rect();
        tpaint.getTextBounds(uppertest, 0, uppertest.length(), rect);
        int upperwidth = rect.width();//文字宽
        int upperheight = rect.height();//文字高
        canvas.drawText(uppertest,controlswidth/2-upperwidth/2,controlsheight/2,tpaint);

        Rect rmect = new Rect();
        tpaint.getTextBounds(underpartwordtext, 0, underpartwordtext.length(), rmect);
        int underpartwordwidth = rmect.width();//文字宽
        int underpartwordheight = rmect.height();//文字高
        canvas.drawText(underpartwordtext,controlswidth/2-underpartwordwidth/4 + 20,controlsheight/2+smallroundradius/2,underparpaint);
    }

    //todo 绘制圆环
    private void drawRing(Canvas canvas) {
        canvas.drawArc(controlmargin+ringwidth/2,controlmargin+ringwidth/2,controlswidth-controlmargin-ringwidth/2,controlsheight-controlmargin-ringwidth/2,180,ringsweepAngle,false,rpaint);
    }
    // todo 绘制小内圆
    private void drawSmallRound(Canvas canvas) {
        canvas.drawCircle(controlswidth/2,controlsheight/2,smallroundradius,npaint);
    }
    // todo 绘制大背景圆
    private void drawGreatCircler(Canvas canvas) {
        canvas.drawCircle(controlswidth/2,controlsheight/2,greatcircleradius,mpaint);

    }
    // todo 绘制心电图
    private void drawElectrocardiogram(Canvas canvas) {
        if(data.size() > 1){
            for(int i=1; i<data.size(); i++){
                NLogger.e("tag","========="+i);
                canvas.drawLine(controlmargin+ringwidth+Xoffset*(i-1), controlsheight/2 - data.get(i-1) * YScale,
                        controlmargin+ringwidth+Xoffset*i, controlsheight/2 - data.get(i) * YScale, epaint);
            }
        }
        //canvas.drawPath(mpath,epaint);
    }


    private boolean isparity(int number){
        if(number%2 == 0){  //是一个偶数！
            return  true;
        }else{  //是一个奇数！
            return false;
        }
    }
    //开始心电图
    public void startTestElectrocardiogram(){
        isElectrocardiogram = true;
       // flag = false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isElectrocardiogram){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }finally {

                        if(data.size() >= MaxDataSize){
                            data.remove(0);
                        }
                        data.add(new Random().nextInt(3));
                        mhandler.sendEmptyMessage(0);
                    }
                }
            }
        }).start();
    }
    //停止测试
    public void stopElectrocardiogram(){
        isElectrocardiogram = false;
       // flag =true;
    }
    public void startAnim(final float mringsweepAngle){
       // flag = false;
        // 创建 ObjectAnimator 对象
        animator = ObjectAnimator.ofFloat(MyCardiacDetectionCustomView.this, "ringsweepAngle", 0, mringsweepAngle);
        animator.setDuration(180000);
        animator.setInterpolator(new LinearInterpolator());
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                if(mAnimationListener != null){
                    mAnimationListener.onstart();
                   flag = false;
                    invalidate();
                }

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if(mAnimationListener != null){
                    mAnimationListener.onEnd();
                   // flag = false;
                  //  NLogger.e("TAG","onAnimationStart ============="+flag);
                   invalidate();
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {
                if(mAnimationListener != null){
                    mAnimationListener.onCancel();
                    flag = true;
                    ringsweepAngle = 0.5f;
                    invalidate();
                }

            }

            @Override
            public void onAnimationRepeat(Animator animator) {
                if(mAnimationListener != null){
                    mAnimationListener.onRepeat();
                }
            }
        });
// 执行动画
        animator.start();
    }
    public void  stopAnim(float mringsweepAngle){
        if(animator != null){
           flag =true;
            ringsweepAngle = mringsweepAngle;
            animator.cancel();
            animator = null;

            //invalidate();

        }
    }


    public void setmAnimationListener(MyAnimationListener mAnimationListener) {
        this.mAnimationListener = mAnimationListener;
    }

    private MyAnimationListener mAnimationListener ;

    public void refrsh(){
        ringsweepAngle = 0.5f;
        invalidate();
    }


}
